package com.jie.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jie.dao.GoodsDao;
import com.jie.dao.GoodsEs;
import com.jie.entity.Goods;
import com.jie.entity.GoodsAttrs;
import com.jie.entity.QuerInfo;
import com.jie.service.GoodsAttrsService;
import com.jie.service.GoodsService;
import com.jie.utility.JwtUtils;
import com.jie.utility.FrontInfo;
import com.jie.utility.QueryInfo;
import com.jie.utility.R;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author jie
 * @since 2023-12-29
 */
@RestController
@RequestMapping("/rear-end")
public class GoodsController {
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private GoodsAttrsService attrsService;
    @Autowired
    private RestHighLevelClient client;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 添加商品
     * @param goodsDao
     * @return
     */
    @PostMapping("/addGoods")
    @Transactional
    public R<String> addGoods(@RequestBody GoodsDao goodsDao, HttpServletRequest request) throws IOException {
        String jwt = request.getHeader("Authorization");
        R r = JwtUtils.parseJwt(jwt);
        Map map = r.getMap();
        Integer adminId = (Integer) map.get("adminId");
        goodsDao.setCreateAdminId(adminId);
        Goods goods = new Goods();
        List<GoodsAttrs> manyAtts = goodsDao.getManyAttrs();
        List<GoodsAttrs> onlyAtts = goodsDao.getOnlyAttrs();
        BeanUtils.copyProperties(goodsDao,goods);
        if(goods.getGoodsNumber()<=0){
            goods.setGoodsState("0");
            goodsDao.setGoodsState("0");
        }
        boolean save = goodsService.save(goods);
        if(save){
            for (GoodsAttrs manyAtt:manyAtts) {
                manyAtt.setGoodsId(goods.getGoodsId());
                manyAtt.setIsMany(1);
            }
            for (GoodsAttrs onlyAtt:onlyAtts) {
                onlyAtt.setGoodsId(goods.getGoodsId());
                onlyAtt.setIsMany(0);
            }if(manyAtts.size()>0){
                boolean b = attrsService.saveBatch(manyAtts);
                if(!b){
                    return R.error("添加失败");
                }
            }
           if(onlyAtts.size()>0){
               boolean b1 = attrsService.saveBatch(onlyAtts);
               if(!b1){
                   return R.error("添加失败");
               }
           }
            R<GoodsDao> goodsDaoR = goodsService.goodsByid(goods.getGoodsId());
            GoodsDao data = goodsDaoR.getData();
            IndexRequest indexRequest = new IndexRequest("goods").id(data.getGoodsId());
            indexRequest.source(JSON.toJSONString(data), XContentType.JSON);
            client.index(indexRequest, RequestOptions.DEFAULT);
            return R.success("添加成功");
        }
        return R.error("添加失败！");
    }

    /**
     * 分页查询所有数据
     * @param queryInfo
     * @return
     */
    @GetMapping("/goods")
    public R<List<GoodsDao>> goods(QueryInfo queryInfo,HttpServletRequest request){
        String jwt = request.getHeader("Authorization");
        R r = JwtUtils.parseJwt(jwt);
        Map map = r.getMap();
        Integer adminId;
        Integer type=(Integer) map.get("type");
        if(type==3){
            adminId= (Integer) map.get("createAdminId");
        }else {
           adminId  = (Integer) map.get("adminId");
        }

        return goodsService.goods(queryInfo,adminId);
    }

    /**
     * 修改商品
     * @param goodsDao
     * @return
     */
    @PutMapping("/updateGoods")
    @Transactional
    public R<String> updateGoods(@RequestBody GoodsDao goodsDao) throws IOException {
        Goods goods = new Goods();
        List<GoodsAttrs> manyAtts = goodsDao.getManyAttrs();
        List<GoodsAttrs> onlyAtts = goodsDao.getOnlyAttrs();
        BeanUtils.copyProperties(goodsDao,goods);
        boolean save = goodsService.updateById(goods);
        if(save){
            if(manyAtts.size()>0){
                boolean b = attrsService.updateBatchById(manyAtts);
                if(!b){
                    return R.error("修改失败");
                }
            }
            if(onlyAtts.size()>0){
                boolean b1 = attrsService.updateBatchById(onlyAtts);
                if(!b1){
                    return R.error("修改失败");
                }
            }
            UpdateRequest request = new UpdateRequest("goods", goodsDao.getGoodsId());
            // 使用 XContentBuilder 构建要更新的数据
            XContentBuilder builder = XContentFactory.jsonBuilder();
            List<String> suggestion=new ArrayList<>();
            suggestion.add(goodsDao.getGoodsName());
            builder.startObject()
                    .field("goodsName", goodsDao.getGoodsName())
                    .field("goodsPrice", goodsDao.getGoodsPrice())
                    .field("goodsWeight", goodsDao.getGoodsWeight())
                    .field("goodsNumber", goodsDao.getGoodsNumber())
                    .field("goodsCat", goodsDao.getGoodsCat())
                    .field("pics", goodsDao.getPics())
                    .field("detailPics", goodsDao.getDetailPics())
                    .field("suggestion",suggestion)
                    .startArray("manyAttrs");
            attr(manyAtts, builder);
            builder.endArray()
                    .startArray("onlyAttrs");
            attr(onlyAtts, builder);

            builder.endArray()
                    .endObject();

            request.doc(builder);
            client.update(request,RequestOptions.DEFAULT);
            return R.success("修改成功");
        }
        return R.error("修改失败！");
    }
    @GetMapping("/findidfigure/{id}")
    public R<GoodsDao> findidfigure(@PathVariable String id){
        GoodsDao goodsDao = goodsService.findidfigure(id);
        if(goodsDao==null){
            R.error("没有查询到该商品");
        }
        return R.success(goodsDao);
}


    /**
     * 删除商品
     * @param goodsId
     * @return
     */
       @DeleteMapping("/delGoods")
       @Transactional
      public R<String> delGoods(String goodsId) throws IOException {
        boolean b = goodsService.removeById(goodsId);
        LambdaQueryWrapper<GoodsAttrs> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(GoodsAttrs::getGoodsId,goodsId);
        boolean remove = attrsService.remove(queryWrapper);
        if(b&&remove){
            DeleteRequest request = new DeleteRequest("goods", goodsId);
            client.delete(request,RequestOptions.DEFAULT);
            return R.success("删除商品成功！");
        }
        return R.success("删除商品失败！");
    }

    /**
     * 前端查询商品信息
     * @param frontInfo
     * @return
     */
    @GetMapping("/figures")
    public R<List<GoodsDao>> goodsByES(FrontInfo frontInfo) throws IOException {
        return goodsService.goodsByES(frontInfo);
    }

    /**
     *
     * 根据商品名查询数据
     * @param queryInfo
     * @return
     */
    @GetMapping("/figures1")
    public R<List<GoodsDao>> goodsByEs1( QueryInfo queryInfo){

        try {
            SearchRequest request = new SearchRequest("goods");
            if(queryInfo.getQuery()!=null&&queryInfo.getQuery().length()>0){
                request.source().query(QueryBuilders.matchQuery("goodsName",queryInfo.getQuery()));
            }
            request.source().from((queryInfo.getPagenum()-1)*queryInfo.getPagesize()).size(queryInfo.getPagesize());
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            return goodsService.getListR(response);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 根据创建者查询商品信息
     * @param goods
     * @return
     */
    @GetMapping("/figures2")
    public R<List<GoodsDao>> getGoodsforAdmin(Goods goods){
        if(goods!=null){
   return R.success(goodsService.getGoodsforAdmin(goods));}
        return R.error("请添加创建者id来进行查询");
}
    /**
     * 自动补全查询
     * @param name
     * @return
     */
    @GetMapping("/mySuggestion")
    public R<List<String>> mySuggestion(String name){
      List<String> inputs= goodsService.mySuggestion(name);
      return R.success(inputs);
     }
     /**
     * 数据统计使用的商品数据
     *
     */
    @GetMapping("/getGoods")
    public  R<List<Goods>> getGoods( HttpServletRequest request){
        String jwt = request.getHeader("Authorization");
        if(StringUtils.isEmpty(jwt)){
            return R.error("NOTLOGIN");
        }
        R r = JwtUtils.parseJwt(jwt);
        if(r.getCode()==0){
            return R.error("NOTLOGIN");
        }
        Integer createAdminId;
        Map map = r.getMap();
        Integer type= (Integer) map.get("type");
        if(type==3){
            createAdminId= (Integer) map.get("createAdminId");
        }else {
            createAdminId= (Integer) map.get("adminId");
        }
        LambdaQueryWrapper<Goods> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Goods::getCreateAdminId,createAdminId);
        List<Goods> list = goodsService.list(lambdaQueryWrapper);
        return R.success(list);
    }
    /**
     * 设置es修改数组
     * @param atts
     * @param builder
     * @throws IOException
     */
    private void attr(List<GoodsAttrs> atts, XContentBuilder builder) throws IOException {
        for (GoodsAttrs attr : atts) {

            builder.startObject()
                    .field("id",attr.getId())
                    .field("attrId",attr.getAttrId())
                    .field("attrName",attr.getAttrName())
                    .field("attrVals",attr.getAttrVals())
                    .field("addPrice",attr.getAddPrice())
                    .field("manyPics",attr.getManyPics())
                    .field("isMany",attr.getIsMany())
                    .field("goodsId",attr.getGoodsId())
                    .field("checkeds",attr.getCheckeds())

                    .endObject();
        }
    }

}

